﻿using OperationPlugins.Mvc.Filters;
using System.Web.Mvc;
using TimeProject.Engine;
using TimeProject.Engine.DbContent;
using TimeProject.Engine.DbModels;
using TimeProject.WebSite.ViewModels;
using WebMatrix.WebData;

namespace TimeProject.WebSite.Controllers
{
    public partial class TimeProjectController
    {
        [HttpGet]
        [CurrentOperation(TimeProjectOperations.Login)]
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (Request.IsAuthenticated)
            {
                return RedirectToLocal("Index");
            }

            LoginViewModel vm = new LoginViewModel {ReturnUrl = returnUrl};
            return View(vm);
        }

        [HttpPost]
        [CurrentOperation(TimeProjectOperations.Login)]
        [AllowAnonymous]
        public ActionResult Login(LoginViewModel vm)
        {
            return Json(vm, () =>
            {
                if (WebSecurity.Login(vm.Username, vm.Password, vm.RememberMe))
                {
                    Db.GetTimestampData = () => new TimeProjectDbContext.TimestampData
                    {
                        RequestUsername = vm.Username,
                        RequestTimestamp = RequestContext.Current.RequestTimestamp
                    };

                    User user = Db.GetUser(vm.Username);

                    if (user != null)
                    {
                        Db.UserActivities.Add(new UserActivity { UserId = user.Id, Type = UserActivityType.Login });

                        if (SaveDbContext() == false)
                        {
                            WebSecurity.Logout();
                            vm.Messages.AddErrorMessage("The username or password provided is incorrect.");
                        }
                        else
                        {
                            vm.RedirectTo(vm.ReturnUrl ?? "Index");
                        }
                    }
                    else
                    {
                        WebSecurity.Logout();
                        vm.Messages.AddErrorMessage("The username or password provided is incorrect.");
                    }
                }
                else
                {
                    vm.Messages.AddErrorMessage("The username or password provided is incorrect.");
                }
            });
        }

    }
}